package com.bj58.mis.apm.server.kylin.common.hllc;

import java.io.Serializable;
import java.util.*;

public class SparseRegister implements Register, Serializable {
    private Map<Integer, Byte> sparseRegister = new TreeMap();

    public SparseRegister() {
    }

    public DenseRegister toDense(int p) {
        DenseRegister dr = new DenseRegister(p);
        Iterator i$ = this.sparseRegister.entrySet().iterator();

        while(i$.hasNext()) {
            Map.Entry<Integer, Byte> entry = (Map.Entry)i$.next();
            dr.set((Integer)entry.getKey(), (Byte)entry.getValue());
        }

        return dr;
    }

    public void set(int pos, byte value) {
        this.sparseRegister.put(pos, value);
    }

    public byte get(int pos) {
        Byte b = (Byte)this.sparseRegister.get(pos);
        return b == null ? 0 : b;
    }

    public void merge(Register another) {
        assert another.getRegisterType() != RegisterType.DENSE;

        if (another.getRegisterType() == RegisterType.SPARSE) {
            SparseRegister sr = (SparseRegister)another;
            Iterator i$ = sr.sparseRegister.entrySet().iterator();

            while(i$.hasNext()) {
                Map.Entry<Integer, Byte> entry = (Map.Entry)i$.next();
                byte v = this.get((Integer)entry.getKey());
                if ((Byte)entry.getValue() > v) {
                    this.sparseRegister.put(entry.getKey(), entry.getValue());
                }
            }
        } else if (another.getRegisterType() == RegisterType.SINGLE_VALUE) {
            SingleValueRegister sr = (SingleValueRegister)another;
            if (sr.getSize() > 0) {
                byte v = this.get(sr.getSingleValuePos());
                if (sr.getValue() > v) {
                    this.sparseRegister.put(sr.getSingleValuePos(), sr.getValue());
                }
            }
        }

    }

    public void clear() {
        this.sparseRegister.clear();
    }

    public int getSize() {
        return this.sparseRegister.size();
    }

    public RegisterType getRegisterType() {
        return RegisterType.SPARSE;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (obj == null) {
            return false;
        } else if (this.getClass() != obj.getClass()) {
            return false;
        } else {
            SparseRegister other = (SparseRegister)obj;
            if (this.sparseRegister == null) {
                if (other.sparseRegister != null) {
                    return false;
                }
            } else if (!this.sparseRegister.equals(other.sparseRegister)) {
                return false;
            }

            return true;
        }
    }

    @Override
    public int hashCode(){
        return super.hashCode();
    }

    public Collection<Map.Entry<Integer, Byte>> getAllValue() {
        return Collections.unmodifiableCollection(this.sparseRegister.entrySet());
    }
}